import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=UTF-8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1234");


        Connection connection = dataSource.getConnection();


        String sql = "select * from students where age = 18";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);


        ResultSet resultSet = preparedStatement.executeQuery();

        // 执行对结果集的操作，比如遍历结果集并输出
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");

            System.out.println("Name: " + name + ", Age: " + age);
        }

        // 关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
